package com.jason.kotlin.gank.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.GravityCompat
import androidx.databinding.DataBindingUtil
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.ViewModelProviders
import com.jason.kotlin.gank.GankConstant
import com.jason.kotlin.gank.LocationHelper
import com.jason.kotlin.gank.R
import com.jason.kotlin.gank.databinding.GankActivityHomeBinding
import com.jason.kotlin.gank.model.CaiYunRealtimeBean
import com.jason.kotlin.gank.util.CaiyunUtils
import com.jason.kotlin.gank.util.WeatherUtils
import com.jason.kotlin.gank.viewmodel.WeatherViewModel
import com.jason.library.common.ext.observe
import com.jason.library.common.ext.showToast
import com.jason.library.common.ext.start
import com.jason.library.common.util.CLogUtils


class GankHomeActivity : AppCompatActivity(), View.OnClickListener {

    lateinit var drawerLayout: DrawerLayout

    private lateinit var binding: GankActivityHomeBinding

    private lateinit var weatherIv: ImageView
    private lateinit var weatherRl: RelativeLayout
    private lateinit var temperatureTv: TextView
    private lateinit var windScaleTv: TextView
    private lateinit var humidityTv: TextView
    private lateinit var feelsLikeTv: TextView
    private lateinit var windDirectionTv: TextView
    private lateinit var weatherTv: TextView
    private lateinit var cityNameTv: TextView
    private lateinit var chooseCityLL: LinearLayout

    private lateinit var locationManager: LocationManager
    private lateinit var locationProvider: String

    private var countryName: String? = null
    private var provinceName: String? = null
    private var cityName: String? = null

    //纬度
    private var latitude: Double = 0.0

    //经度
    private var longitude: Double = 0.0


    private val locationCodeReq = 1001

    private lateinit var viewModel: WeatherViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DataBindingUtil.setContentView<GankActivityHomeBinding>(this, R.layout.gank_activity_home)
            .let {
                it.homeDelegate = GankHomeDelegate(this@GankHomeActivity)
                binding = it

                binding.toolbar.setNavigationIcon(R.drawable.gank_icon_menu_white)

                setSupportActionBar(binding.toolbar)
                binding.toolbar.setTitleTextColor(resources.getColor(R.color.white))
            }
        drawerLayout = binding.drawerLayout
        binding.homeDelegate!!.setMenuSelection(R.id.nav_home, "首页")

        viewModel = ViewModelProviders.of(this).get(WeatherViewModel::class.java)

        observe(viewModel.dataCaiYunWeather) {
            updateWeather(it)
        }

        initLocation()
        initWeather()
    }

    private fun initLocation() {
        //1.获取位置管理器
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            initLocationAboveM()
        } else {
            initLocationLowM()
        }
    }

    private fun initLocationProvider() {
        //2.获取位置提供器，GPS或是NetWork
        val providers: List<String> = locationManager.getProviders(true)
        when {
            providers.contains(LocationManager.GPS_PROVIDER) -> {
                //如果是GPS
                locationProvider = LocationManager.GPS_PROVIDER
                //Log.v("TAG", "定位方式GPS")
            }
            providers.contains(LocationManager.NETWORK_PROVIDER) -> {
                //如果是Network
                locationProvider = LocationManager.NETWORK_PROVIDER
                //Log.v("TAG", "定位方式Network")
            }
            else -> {
                Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show()
                return
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun initLocationAboveM() {
        //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
        if (hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            && hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
        ) {
            initLocationProvider()
            //3.获取上次的位置，一般第一次运行，此值为null
            val location: Location? = locationManager.getLastKnownLocation(locationProvider)
            if (location != null) {
                Log.v(
                    "TAG",
                    "获取上次的位置-经纬度：" + location.longitude
                        .toString() + "   " + location.latitude
                )
                val address = LocationHelper.getAddress(this@GankHomeActivity, location)
                if (!address.isNullOrEmpty()) {
                    cityName = address[0].locality
                    provinceName = address[0].adminArea
                    countryName = address[0].countryName
                    longitude = address[0].longitude
                    latitude = address[0].latitude
                    loadWeatherData()
                }
            } else {
                //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
                locationManager.requestLocationUpdates(
                    locationProvider,
                    3000, 1f, locationListener
                )
            }
        } else {
            //请求权限
            ActivityCompat.requestPermissions(
                this, arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ), locationCodeReq
            )
        }
    }

    @SuppressLint("MissingPermission")
    private fun initLocationLowM() {
        initLocationProvider()

        val location = locationManager.getLastKnownLocation(locationProvider)
        if (location != null) {
            Log.v(
                "TAG",
                "获取上次的位置-经纬度：" + location.longitude + "   " + location.latitude
            )
            val address = LocationHelper.getAddress(this@GankHomeActivity, location)
            if (!address.isNullOrEmpty()) {
                cityName = address[0].locality
                provinceName = address[0].adminArea
                countryName = address[0].countryName
                longitude = address[0].longitude
                latitude = address[0].latitude
                loadWeatherData()
            }
        } else {
            //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
            locationManager.requestLocationUpdates(locationProvider, 3000, 1f, locationListener)
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {

        if (requestCode == locationCodeReq) {
            initLocationAboveM()
        }
    }


    private fun hasPermission(permissionName: String) =
        ActivityCompat.checkSelfPermission(
            this,
            permissionName
        ) == PackageManager.PERMISSION_GRANTED

    var locationListener: LocationListener = object : LocationListener {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        override fun onStatusChanged(
            provider: String,
            status: Int,
            extras: Bundle
        ) {
        }

        // Provider被enable时触发此函数，比如GPS被打开
        override fun onProviderEnabled(provider: String) {}

        // Provider被disable时触发此函数，比如GPS被关闭
        override fun onProviderDisabled(provider: String) {}

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        override fun onLocationChanged(location: Location) {
            //如果位置发生变化，重新显示地理位置经纬度
            showToast(
                location.longitude.toString() + " " +
                        location.latitude + ""
            )
            Log.v(
                "TAG",
                "监视地理位置变化-经纬度：" + location.longitude + "   " + location.latitude
            )
        }
    }

    private fun initWeather() {
        val headerLayout = binding.navigationView.inflateHeaderView(R.layout.gank_drawer_header)
        weatherIv = headerLayout.findViewById(R.id.header_iv_weather)
        weatherRl = headerLayout.findViewById(R.id.rl_weather)
        temperatureTv = headerLayout.findViewById(R.id.header_tv_temperature)
        windScaleTv = headerLayout.findViewById(R.id.tv_weather_wind_scale)
        humidityTv = headerLayout.findViewById(R.id.tv_weather_humidity)
        feelsLikeTv = headerLayout.findViewById(R.id.tv_weather_feels_like)
        windDirectionTv = headerLayout.findViewById(R.id.tv_weather_wind_direction)
        weatherTv = headerLayout.findViewById(R.id.header_tv_weather)
        cityNameTv = headerLayout.findViewById(R.id.header_tv_city_name)
        chooseCityLL = headerLayout.findViewById(R.id.header_ll_choose_city)
        weatherRl.setOnClickListener(this)
    }

    private fun loadWeatherData() {
        val location = "$longitude,$latitude"
        viewModel.getWeatherFromCaiYun(location)
    }

    private fun updateWeather(data: CaiYunRealtimeBean) {
        CLogUtils.i(data.toString())
        //天气
        val weather = CaiyunUtils.getWeatherText(data.skycon)
        //城市
        cityNameTv.text = "$provinceName-$cityName"
        //赋值
        temperatureTv.text = "${data.temperature}°"
        weatherTv.text = weather
        weatherIv.setImageResource(WeatherUtils.getWeatherResId(weather))
        //其他数据可能没有
        windDirectionTv.text = "${CaiyunUtils.getWindDirection(data.wind.direction)}风"
        windScaleTv.text = "${CaiyunUtils.getWindScale(data.wind.speed)}级"
        feelsLikeTv.text = "${data.apparentTemperature}°"
        humidityTv.text = "${data.humidity * 100}%"
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                binding.drawerLayout.openDrawer(GravityCompat.START)
                return true
            }
            R.id.home_search -> {
                start(GankSearchActivity::class.java)
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main_toolbar, menu)
        return true
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.rl_weather -> {
                val data = Bundle()
                data.putString(GankConstant.KEY_PROVINCE_NAME, provinceName)
                data.putString(GankConstant.KEY_CITY_NAME, cityName)
                val location = "$longitude,$latitude"
                data.putString(GankConstant.KEY_LOCATION, location)
                start(WeatherActivity::class.java, data)
            }
        }



    }


}